package cn.stronglink.asset.message.mq.dam.handle;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import cn.stronglink.asset.message.mq.dam.entity.IScreenCommandFactory;
import cn.stronglink.asset.message.mq.dam.entity.ScreenCommandEntity;
import cn.stronglink.asset.message.mq.dam.entity.dacai.UpdateArrayTextCommandFactory;
import cn.stronglink.asset.message.mq.dam.message.MQMessageOfDAM;
import cn.stronglink.asset.message.mq.topic.ReaderInfoSender;
import cn.stronglink.asset.module.dam.service.DamService;
import cn.stronglink.asset.module.dam.service.IDamService;
import cn.stronglink.suite.core.util.ByteUtil;
import cn.stronglink.suite.core.util.ContextUtils;

public class AssetModelBindUHeightHandle extends AbstractReturnExceptionHandle{
	protected final static String TOPIC_NAME = "serviceToDam";
	protected final static String ACTION_CODE = "screenRequest";
	protected final static String SEND_ACTION_CODE= "screenCommand";
	protected IDamService damService =(DamService)ContextUtils.getBean("sensorService");
	private ReaderInfoSender topicSender = (ReaderInfoSender) ContextUtils.getBean("readerInfoSender");
	private final static short DIALOG_ID = 1;
	private final static short DIALOG_SCREEN_ID = 14;
	private long lastReceiveTime =0;
	private final static int MAX_INTERVAL_TIME = 3000;
	private boolean isReceiveAssetModelIdCommand=false;
	private boolean isReceiveUHeightCommand=false;
	private boolean isReceiveBtnCommand = false;
	private String assetModelId = "";
	private int uHeight = 0;
	
	@Override
	public boolean isHandle(MQMessageOfDAM msg) {
		ScreenCommandEntity entity = (ScreenCommandEntity) msg.getAwsPostdata();
		if(entity!=null) {
			int controlId = hexStringToControlId(entity.getCommand());
			if(entity.getCommand().indexOf("EEB111000D")==0 
					&& ((controlId>0 && controlId<50)||(controlId>100 && controlId<117))) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void handleMessage(MQMessageOfDAM msg) {
		if(System.currentTimeMillis()-lastReceiveTime>MAX_INTERVAL_TIME) {
			this.clearData();
		}
		
		ScreenCommandEntity entity = (ScreenCommandEntity) msg.getAwsPostdata();
		Map<Short,String> map = new HashMap<>();
		try {
		if(entity!=null) {
			int controlId = hexStringToControlId(entity.getCommand());
			System.out.println("command==="+entity.getCommand());
			if(entity.getCommand().indexOf("EEB111000D")==0 
					&& ((controlId>0 && controlId<50)||(controlId>100 && controlId<117)))  {
				if(!this.isReceiveAssetModelIdCommand&&controlId>0 && controlId<50 && (controlId-1)%3==0) {
					this.isReceiveAssetModelIdCommand = true;
					String assetModelIdCommandStr = entity.getCommand().substring(16, entity.getCommand().length()-2);
					System.out.println("assetModelIdCommandStr==="+assetModelIdCommandStr);
					if(!assetModelIdCommandStr.equals("20")) {
						this.assetModelId = new String(ByteUtil.hexStringToBytes(assetModelIdCommandStr)).trim();
					}
					System.out.println("assetModelId==="+assetModelId);
				}else if(!this.isReceiveUHeightCommand&&controlId>0 && controlId<50 && controlId%3==0){
					this.isReceiveUHeightCommand = true;
					String uHeightCommandStr = entity.getCommand().substring(16, entity.getCommand().length()-2);
					System.out.println("uHeightCommandStr==="+uHeightCommandStr);
					if(!uHeightCommandStr.equals("20")) {
						this.uHeight = Integer.parseInt(new String(ByteUtil.hexStringToBytes(uHeightCommandStr)).trim());
					}
					System.out.println("uHeight==="+uHeight);
				}else if(!this.isReceiveBtnCommand&&controlId>100 && controlId<117) {
					this.isReceiveBtnCommand = true;
				}
				
				if(this.isReceiveAssetModelIdCommand && this.isReceiveUHeightCommand && this.isReceiveBtnCommand) {
					if(assetModelId.equals("")||assetModelId.isEmpty()) {
						// 未找到该机柜
						map.put(DIALOG_ID, "资产型号id不能为空!");
					}else if(uHeight==0) {
						map.put(DIALOG_ID, "u高不能为空!");
					}else {
						damService.updateAssetModelUHeight(assetModelId,uHeight);
						map.put(DIALOG_ID, "id为["+assetModelId+"]的型号成功设置u高为"+uHeight);
					}
					sendCommandToScreen(entity.getRackConverCode(),map);
					map.clear();
					this.clearData();
				}
			}
		}
		lastReceiveTime = System.currentTimeMillis();
		}catch (Exception e) {
			e.printStackTrace();
			map.put(DIALOG_ID, e.getMessage()+"");
			try {
				sendCommandToScreen(entity.getRackConverCode(),map);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	private void sendCommandToScreen(String rackConverCode, Map<Short, String> map) throws Exception {
		IScreenCommandFactory rackScreenCommandFactroy = new UpdateArrayTextCommandFactory(rackConverCode, DIALOG_SCREEN_ID, map);
		ScreenCommandEntity sc =  rackScreenCommandFactroy.createScreenCommand();
		
		MQMessageOfDAM message = new MQMessageOfDAM();
		message.setActioncode(SEND_ACTION_CODE);
		message.setAwsPostdata(sc);
		message.setTimestamp(System.currentTimeMillis());
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME,json);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,json);
		
		
		ScreenCommandEntity changeScreen =  rackScreenCommandFactroy.changeScreenCommand();
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(SEND_ACTION_CODE);
		msg.setAwsPostdata(changeScreen);
		msg.setTimestamp(System.currentTimeMillis());
		
		String changeScreenJson = JSON.toJSONString(msg);
		topicSender.send(TOPIC_NAME,changeScreenJson);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,changeScreenJson);
		
	}

	private void clearData() {
		this.isReceiveAssetModelIdCommand = false;
		this.isReceiveUHeightCommand = false;
		this.isReceiveBtnCommand = false;
		this.assetModelId = "";
		this.uHeight = 0;	
	}
	
	private int hexStringToControlId(String command) {
		int id = 0;
		if(command.length()>18) {
			id = Integer.parseInt(command.substring(11, 14),16);
		}
		return id;
	}

	
}
